/*  File Name	: Reactor.h
 *  Author		: Pang Jiacai
 *	 E-mail		: 823960168@qq.com
 *  Created on	: 2012-2-2
 *  Description:
 */

#ifndef REACTOR_H_
#define REACTOR_H_
#include "Header.h"
#include "ReactorImpl.h"
#include "EventHandler.h"
#include "SignalHanlder.h"
#include "Lock.h"

class ReactorImpl;
class SignalHanlder;
class EventHandler;

class Reactor
{
public:
	enum
	{
		GET_MASK =1,
		SET_MASK =2,
		ADD_MASK =3,
		CLR_MASK =4
	};

	Reactor(ReactorImpl *impl=NULL);

	virtual ~Reactor();

	static Reactor *instance(void);

	int open(int handle_size =1024,int timer_heap_size=10240,SignalHanlder *sh=NULL,bool only_timer=false);

	int handle_events(int timeout=1000);

	void implement(ReactorImpl *impl);

	int run_reactor_loop(int timeout=1000);

	int end_reactor_loop();

	//reactor run status,1:start 2:stop
	int run_status(void);

	// i/o handler
	int register_handler(int handle,EventHandler *eh,ReactorMask mask);

	/**
	 * this function will call EventHandler::handle_close
	 * so,don't invoke it in EventHandler::handle_close
	 */
	int remove_handler(int handle,EventHandler *eh,ReactorMask mask=EventHandler::ALL_MASK);

	//signal handler
	int register_signal(int signum,EventHandler *eh,bool replace_old=true,EventHandler *old_sh=NULL);

	int remove_signal(int signum,EventHandler *eh);

	//timer
	long schudle_timer(EventHandler *eh,TimeValue delay,TimeValue interval=TimeValue::zero);

	int suspend_timer(long timer_id);

	int resume_timer(long timer_id);

	int cancel_timer(long timer_id);

	int refresh_timer(long timer_id,TimeValue new_time);

	RT_MUTEX &lock(void);

	//1:select  2: epoll
	int reactor_type(void) const;

	ReactorImpl* implement(void);

private:

	ReactorImpl *impl_;

	static Reactor *instance_;

	static RT_MUTEX rt_mutex_;
};

#endif /* REACTOR_H_ */
